<template>
  <div style="padding: 30px;">
    <el-tag
      v-for="(tag,i) in tags"
      :key="i"
      type="info"
      effect="plain"
      closable
      :style="{ color: tag.background, marginRight: '20px' }"
      @close="deleteTag(tag)"
    >
      {{ tag.name }}
      <span class="tag-num">{{ tag.blogNums }}</span>
    </el-tag>
    <el-tag
      v-if="!tagNameAddVisible"
      type="info"
      effect="plain"
      style="width: 100px; cursor: pointer"
      @click="showAddInput"
    >
      +创建新标签
    </el-tag>
    <el-input
      v-if="tagNameAddVisible"
      ref="addTagInput"
      v-model="tagName"
      style="width: 100px"
      size="small"
      @blur="addTag"
      @keyup.enter.native="addTag"
    />
  </div>
</template>

<script>
import {Message} from "element-ui";

const colors = require('@/assets/enums/colors')
import {createTag, deleteTag, queryTagList} from '@/api/blog/tag'

export default {
  name: 'BlogTagList',
  data() {
    return {
      tags: [],
      tagName: '',
      tagNameAddVisible: false
    }
  },
  created() {
    this.setTags()
  },
  methods: {
    setTags() {
      queryTagList({'queryBlogNum': true}).then(resp => {
        this.tags = []
        resp.data.list.forEach(tag => {
          tag.background = this.randomColor()
          this.tags.push(tag)
        })
      })
    },
    deleteTag(tag) {
      deleteTag(tag.id).then(resp => {
        this.setTags()
        Message({
          message: '删除成功',
          type: 'success',
          duration: 2 * 1000
        })
      })
    },
    randomColor() {
      const r = parseInt(Math.random() * colors.length)
      return colors[r]
    },
    showAddInput() {
      this.tagNameAddVisible = true
      this.$nextTick(() => {
        setTimeout(() => {
          this.$refs.addTagInput.focus()
        }, 10)
      })
    },
    addTag() {
      this.tagNameAddVisible = false
      if (this.tagName && this.tagName !== '') {
        createTag({name: this.tagName}).then(resp => {
          this.tagName = ''
          this.setTags()
        })
      }
    }
  }

}
</script>

<style scoped>
.tag-num {
  background-color: #a9a84c;
  border: 1px solid whitesmoke;
  border-radius: 5px;
  padding: 2px;
  color: whitesmoke;
}
</style>
